package calao.storage;

import java.util.Iterator;
import java.util.BitSet;

public class Index
implements Iterable<Field>
{

	class FieldIterator	implements Iterator<Field> {
		int i = 0;
		public boolean hasNext() {
			return i<fields.length;
		}
		public Field next() {
			return fields[i++];
		}
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

	final Table table;
	final BitSet fieldsRef;
	final boolean isKey;
	final int size;
	final Field[] fields;

	Index(Table table, Field[] fields, boolean isKey)
	{
		this.table = table;
		fieldsRef = new BitSet(fields.length);
		for (Field field : fields) {
			fieldsRef.set(field.index);
		}
		this.isKey = isKey;
		this.size = fields.length;
		this.fields = fields;
	}

	public boolean refersTo(Field field)
	{
		return fieldsRef.get(field.index);
	}

	public boolean isKeyIndex()
	{
		return isKey;
	}

	public Iterator<Field> iterator() {
		return new FieldIterator();
	}

	public Field getFirstField()
	{
		return table.getField(fieldsRef.nextSetBit(0));
	}

	public int getFieldCount()
	{
		return size;
	}

	public Field getField(int position) 
	{
		return fields[position];
	}

	public int getPosition(Field field) 
	{
		for (int pos=0; pos<fields.length; pos++) {
			if (fields[pos]==field) return pos;
		}
		return -1;
	}
	
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();
		for (Field field : fields) {
			if (buffer.length()>0) buffer.append('+');
			buffer.append(field.getName());
		}
		return buffer.toString();
	}

}
